﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ExtendedLayerRules.Models;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Mvc;
using Orchard.Widgets.Services;

namespace ExtendedLayerRules.Providers
{
    public class ContentTypeWithDisplayRuleProvider : IRuleProvider
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWorkContextAccessor _workContextAccessor;

        public ContentTypeWithDisplayRuleProvider(IHttpContextAccessor httpContextAccessor, IWorkContextAccessor workContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _workContextAccessor = workContextAccessor;
        }

        public void Process(RuleContext ruleContext)
        {
            if (!String.Equals(ruleContext.FunctionName, "contenttypewithdisplay", StringComparison.OrdinalIgnoreCase) ||
                ruleContext.Arguments[0] == null || String.IsNullOrWhiteSpace(ruleContext.Arguments[0].ToString()))
            {
                return;
            }
            ruleContext.Result = false;
            string typeParam = ruleContext.Arguments[0].ToString();
            string displayParam = ruleContext.Arguments[1] != null ? ruleContext.Arguments[1].ToString() : string.Empty;
            List<ContentTypeWithDisplayItem> ContentTypeWithDisplayItems = _workContextAccessor.GetContext().GetState<List<ContentTypeWithDisplayItem>>("ContentTypeWithDisplayItems");
            if (ContentTypeWithDisplayItems != null && ContentTypeWithDisplayItems.Count > 0)
            {
                foreach (var content in ContentTypeWithDisplayItems)
                {
                    if (content.ContentType.Equals(typeParam, StringComparison.CurrentCultureIgnoreCase) && (content.DisplayType == string.Empty || content.DisplayType.Equals(displayParam, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        ruleContext.Result = true;
                        return;
                    }
                }
            }
        }
    }
}